package com.withoutwords.ui.custom;

import java.util.ArrayList;
import java.util.Random;

import com.withoutwords.R;
import com.withoutwords.engine.Guess;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;

public class GuessesBoardLayout extends RelativeLayout implements IGuessClickListener {

	//final static int maxGuesses= 16;
	IGuessClickListener guessListener;
	boolean bApproveEnabled;
	ArrayList<GuessLayout> guessesLayouts;
	
	public void setApproveEnabled(boolean bApproveEnabled) {
		this.bApproveEnabled = bApproveEnabled;
	}
	public void setGuessListener(IGuessClickListener guessListener) {
		this.guessListener = guessListener;
	}
	public GuessesBoardLayout(Context context)
	{
		super(context);
		init();

	}
	public GuessesBoardLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
		// TODO Auto-generated constructor stub
	}
	void init()
	{
		guessesLayouts = new ArrayList<GuessLayout>();
		LayoutInflater inf =  LayoutInflater.from(getContext());
		inf.inflate(R.layout.guessboard, this);
		ViewGroup rly = (ViewGroup)this.getChildAt(0);
		for(int i =0 ; i< rly.getChildCount() ; i++)
		{
			View v  = rly.getChildAt(i);
			if(GuessLayout.class.isInstance(v))
			{
				v.setVisibility(INVISIBLE);
				guessesLayouts.add((GuessLayout)v);
			}
		}
		
	}
	
	GuessLayout getRandomGuessLayout()
	{
		Random rand = new Random(hashCode());
		int nRandomIndex = rand.nextInt(guessesLayouts.size());
		GuessLayout gly = guessesLayouts.get(nRandomIndex);
		while(gly.getVisibility() == VISIBLE)
		{
			nRandomIndex = rand.nextInt(guessesLayouts.size());
			gly = guessesLayouts.get(nRandomIndex);
			
		}
		gly.setVisibility(VISIBLE);
		return gly;
	}
	public void addGuess(Guess guess)
	{
		GuessLayout gl = getRandomGuessLayout();
		gl.setGuess(guess, this, bApproveEnabled);
		gl.invalidate();
			
	}
	@Override
	public void onActionApprovedClicked(Guess guess) {
	//	guessesLayouts.remove(guess);
		if(guessListener != null)
		{
			guessListener.onActionApprovedClicked(guess);
		}
		invalidate();
	}
	@Override
	public void onActionDeclinedClicked(Guess guess) {
		//guessesLayouts.remove(guess);
		if(guessListener != null)
		{
			guessListener.onActionDeclinedClicked(guess);
		}
		invalidate();
		
	}

}
